<template>
  <el-dialog
    :model-value="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="true"
    title="设计表单"
    @close="handleClose"
  >
    <div v-if="showForm === 0">
      <el-form ref="formRef" :model="createData.data">
        <div v-for="i in num" :key="i" class="my-2">
          <el-form-item>
            <el-input
              v-model="createData.data.itemName[i]"
              placeholder="请输入字段名"
              clearable
              class="w-1/2"
            >
            </el-input>
            <el-select
              v-model="createData.data.titleValue[i]"
              class="w-1/3 pl-4"
              placeholder="请选择需要添加的表单项"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div
            v-if="createData.data.titleValue[i] === 'input'"
            class="mt-2 ml-2 text-gray-400 text-sm"
          >
            发布后可输入内容
          </div>
          <div
            v-if="createData.data.titleValue[i] === 'select'"
            class="mt-2 ml-2 text-gray-600 text-sm"
          >
            <div
              v-for="j in createData.data.selectNum[i]"
              :key="j"
              class="flex flex-1 items-center w-screen"
            >
              选项名{{ j }}：
              <el-input
                v-model="createData.data.selectName[i][j]"
                class="w-1/6 mt-1"
                placeholder="请输入选项名"
                clearable
              >
              </el-input>
            </div>
            <div>
              <el-button type="primary" text @click="addSelect(i)"
                >添加选项</el-button
              >
              <el-button type="primary" text @click="deleteSelect(i, j)"
                >删除选项</el-button
              >
            </div>
          </div>
          <div
            v-if="createData.data.titleValue[i] === 'radio'"
            class="mt-2 ml-2 text-gray-600 text-sm"
          >
            <div
              v-for="j in createData.data.radioNum[i]"
              :key="j"
              class="flex flex-1 items-center w-screen"
            >
              选项名{{ j }}：
              <el-input
                v-model="createData.data.radioName[i][j]"
                placeholder="请输入选项名"
                clearable
                class="w-1/6 mt-1"
              >
              </el-input>
            </div>
            <div>
              <el-button type="primary" text @click="addRadio(i)"
                >添加选项</el-button
              >
              <el-button type="primary" text @click="deleteRadio(i)"
                >删除选项</el-button
              >
            </div>
          </div>
          <div
            v-if="createData.data.titleValue[i] === 'checkbox'"
            class="mt-2 ml-2 text-gray-600 text-sm"
          >
            <div
              v-for="j in createData.data.checkboxNum[i]"
              :key="j"
              class="flex flex-1 items-center w-screen"
            >
              选项名{{ j }}：
              <el-input
                v-model="createData.data.checkboxName[i][j]"
                placeholder="请输入选项名"
                clearable
                class="w-1/6 mt-1"
              >
              </el-input>
            </div>
            <div>
              <el-button type="primary" text @click="addCheckbox(i)"
                >添加选项</el-button
              >
              <el-button type="primary" text @click="deleteCheckbox(i)"
                >删除选项</el-button
              >
            </div>
          </div>
          <div
            v-if="createData.data.titleValue[i] === 'upload'"
            class="mt-2 ml-2 text-gray-400 text-sm"
          >
            发布后可上传
          </div>
        </div>
        <div>
          <el-tooltip
            class="item"
            effect="light"
            content="添加新组件"
            placement="top"
          >
            <el-button type="primary" text @click="addItem"
              >新增表单项</el-button
            >
          </el-tooltip>

          <el-tooltip
            class="item"
            effect="light"
            content="删除组件"
            placement="top"
          >
            <el-button type="primary" text @click="delectItem"
              >删除表单项</el-button
            >
          </el-tooltip>
        </div>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="preservationForm()"
          >保存表单</el-button
        >
        <el-button type="primary" @click="handleClose()">取消</el-button>
      </div>
    </div>
    <div v-if="showForm === 2">
      <el-form
        ref="formRef"
        :model="dynamicValidateForm.data"
        :rules="dynamicValidateForm.rules"
      >
        <el-form-item prop="name" label="表单名称" label-width="80px">
          <el-input
            v-model="dynamicValidateForm.data.name"
            class="w-full"
            placeholder="请输入表单名称"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="placeholder" label="表单描述" label-width="80px">
          <el-input
            v-model="dynamicValidateForm.data.description"
            class="w-full"
            placeholder="请输入表单描述"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="cid" label="表单分类" label-width="80px">
          <el-select
            v-model="dynamicValidateForm.data.cid"
            placeholder="请选择"
            class="w-full"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button type="primary" @click="changeForm()">返回修改</el-button>

        <el-button type="primary" @click="submitForm()"
          >提交表单基本信息</el-button
        >
        <el-button type="primary" @click="handleClose()">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { watch, reactive, ref, toRefs } from "vue";
import { createCustomForm } from "@/api/footform/custom-form";
import { ElMessage } from "element-plus";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  categoryList: {
    type: Object,
    default: () => ({}),
  },
});

const { visible, categoryList } = toRefs(props);
const num = ref(0);
const createData = reactive({
  data: {
    itemName: [],
    titleValue: [],
    selectNum: [1],
    selectName: [[]],
    radioNum: [1],
    radioName: [[]],
    checkboxNum: [1],
    checkboxName: [[]],
  },
});
const options = [
  {
    value: "input",
    label: "单行输入",
  },
  {
    value: "select",
    label: "下拉选项",
  },
  {
    value: "radio",
    label: "单选按钮",
  },
  {
    value: "checkbox",
    label: "多选按钮",
  },
  {
    value: "upload",
    label: "上传文件",
  },
];

//生成的表单规则
const rule = ref([]);

//增加组件
function addItem() {
  num.value += 1;
  createData.data.itemName.push();
  createData.data.selectNum.push(1);
  createData.data.selectName.push([]);
  createData.data.radioNum.push(2);
  createData.data.radioName.push([]);
  createData.data.checkboxNum.push(2);
  createData.data.checkboxName.push([]);
}
//删除组件
function delectItem() {
  if (num.value > 0) {
    num.value -= 1;
    createData.data.itemName.pop();
    createData.data.selectNum.pop();
    createData.data.selectName.pop();
    createData.data.radioNum.pop();
    createData.data.radioName.pop();
    createData.data.checkboxNum.pop();
    createData.data.checkboxName.pop();
  }
}

//增加下拉框选项
function addSelect(i) {
  createData.data.selectNum[i] = createData.data.selectNum[i] + 1;
}
function deleteSelect(i, j) {
  createData.data.selectNum[i] = createData.data.selectNum[i] - 1;

  alert(createData.data.selectNum[i][j]);
}

function addRadio(i) {
  createData.data.radioNum[i] = createData.data.radioNum[i] + 1;
}
function deleteRadio(i) {
  createData.data.radioNum[i] = createData.data.radioNum[i] - 1;
}

function addCheckbox(i) {
  createData.data.checkboxNum[i] = createData.data.checkboxNum[i] + 1;
}
function deleteCheckbox(i) {
  createData.data.checkboxNum[i] = createData.data.checkboxNum[i] - 1;
}

const createItems = ref({});
const showForm = ref(0);

function preservationForm() {
  if (num.value === 0) {
    ElMessage({
      message: "请添加表单项并填写内容！",
      type: "warning",
    });
    showForm.value = 0;
  } else {
    num.value = 0;
    rule.value = [];
    for (let i = 1; i < createData.data.itemName.length; i++) {
      if (createData.data.titleValue[i] === "select") {
        let h = createData.data.selectName[i].length;
        let options = [];
        for (let j = 1; j < h; j++) {
          options.push({
            value: createData.data.selectName[i][j],
            label: createData.data.selectName[i][j],
          });
        }
        rule.value.push({
          id: num.value++,
          type: createData.data.titleValue[i],
          field: createData.data.itemName[i],
          title: createData.data.itemName[i],
          options: options,
          validate: [{ required: true, message: "请选择", trigger: "blur" }],
        });
      } else if (createData.data.titleValue[i] == "radio") {
        let h = createData.data.radioName[i].length;
        let options = [];
        for (let j = 1; j < h; j++) {
          options.push({
            value: createData.data.radioName[i][j],
            label: createData.data.radioName[i][j],
          });
        }
        rule.value.push({
          id: num.value++,
          type: createData.data.titleValue[i],
          field: createData.data.itemName[i],
          title: createData.data.itemName[i],
          options: options,
          validate: [{ required: true, message: "请选择", trigger: "blur" }],
        });
      } else if (createData.data.titleValue[i] == "checkbox") {
        let h = createData.data.checkboxName[i].length;
        let options = [];
        for (let j = 1; j < h; j++) {
          options.push({
            value: createData.data.checkboxName[i][j],
            label: createData.data.checkboxName[i][j],
          });
        }
        rule.value.push({
          id: num.value++,
          type: createData.data.titleValue[i],
          field: createData.data.itemName[i],
          title: createData.data.itemName[i],
          options: options,
          validate: [
            { type: "array", min: 2, required: true, message: "最少选择2个" },
          ],
        });
      } else if (createData.data.titleValue[i] === "upload") {
        rule.value.push({
          id: num.value++,
          type: "upload",
          field: createData.data.itemName[i],
          title: createData.data.itemName[i],
          value: [],
          props: {
            uploadType: "file",
            type: "file",
            accept: "image/jpg",
            action: "http://119.91.145.64:83/api/file/upload",
            name: "file",
            multiple: true,
          },
          // validate: [
          //   {
          //     required: true,
          //     type: "array",
          //     min: 1,
          //     message: "请上传至少1张图片",
          //     trigger: "change",
          //   },
          // ],
        });
      } else {
        rule.value.push({
          id: num.value++,
          type: createData.data.titleValue[i],
          field: createData.data.itemName[i],
          title: createData.data.itemName[i],
          validate: [
            {
              type: "string",
              required: true,
              message: "请输入内容",
            },
          ],
        });
      }
    }
    showForm.value = 2;
    createItems.value = JSON.stringify(rule.value);
  }
}

const formRef = ref({});

const dynamicValidateForm = reactive({
  data: {
    name: "",
    description: "",
    cid: null,
    status: 0,
    structure: createItems,
  },
  rules: {
    name: [{ required: true, message: "请输入表单名称", trigger: "blur" }],
    cid: [{ required: true, message: "请选择表单分类", trigger: "change" }],
  },
});

const emit = defineEmits(["update:visible", "getList", "update:showForm"]);

async function submitForm() {
  await formRef.value.validate((valid) => {
    if (!valid) {
      return;
    } else {
      createCustomForm(dynamicValidateForm.data);
      showForm.value = 0;
      emit("update:visible", false);
    }
  });
  emit("getList");
}

function changeForm() {
  showForm.value = 0;
}

function handleClose() {
  emit("update:visible", false);
  if (num.value > 0) {
    num.value = 0;
    createData.data.itemName.pop();
    createData.data.selectNum.pop();
    createData.data.selectName.pop();
    createData.data.radioNum.pop();
    createData.data.radioName.pop();
    createData.data.checkboxNum.pop();
    createData.data.checkboxName.pop();
  }
  showForm.value = 0;
  emit("getList");
}

// 每次关闭弹窗，清空表单信息
watch(visible, (newValue) => {
  if (newValue === false) {
    formRef.value.resetFields();
    createItems.value = {};
    dynamicValidateForm.data = {
      name: "",
      description: "",
      cid: null,
      status: 0,
      structure: createItems,
    };
    createData.data.itemName = [];
    createData.data.titleValue = [];
  }
});
</script>

<style lang="scss">
.el-input__inner {
  width: 220px;
  border-top-width: 0px;
  border-left-width: 0px;
  border-right-width: 0px;
  border-bottom-width: 1px;
  /*outline: medium;*/
}
.radio1 .el-input__inner {
  width: 100%;
  border-top-width: 0px;
  border-left-width: 0px;
  border-right-width: 0px;
  border-bottom-width: 1px;
  /*outline: medium;*/
}
.textarea .el-textarea__inner {
  width: 100%;
  border-top-width: 0px;
  border-left-width: 0px;
  border-right-width: 0px;
  border-bottom-width: 1px;
  /*outline: medium;*/
}
</style>
